/*
给定一个单链表，其中的元素按升序排序，将其转换为高度平衡的二叉搜索树。

本题中，一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

给定的有序链表： [-10, -3, 0, 5, 9],

一个可能的答案是：[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树：

      0
     / \
   -3   9
   /   /
 -10  5



*/

//分治
class Solution
{
public:
    ListNode *getMedian(ListNode *left, ListNode *right)
    {
        ListNode *fast = left;
        ListNode *slow = left;
        while (fast != right && fast->next != right)
        {
            fast = fast->next;
            fast = fast->next;
            slow = slow->next;
        }
        return slow;
    }

    TreeNode *buildTree(ListNode *left, ListNode *right)
    {
        if (left == right)
        {
            return nullptr;
        }
        ListNode *mid = getMedian(left, right);
        TreeNode *root = new TreeNode(mid->val);
        root->left = buildTree(left, mid);
        root->right = buildTree(mid->next, right);
        return root;
    }

    TreeNode *sortedListToBST(ListNode *head)
    {
        return buildTree(head, nullptr);
    }
};

//分治 + 中序遍历优化
class Solution
{
public:
    int getLength(ListNode *head)
    {
        int ret = 0;
        for (; head != nullptr; ++ret, head = head->next)
            ;
        return ret;
    }

    TreeNode *buildTree(ListNode *&head, int left, int right)
    {
        if (left > right)
        {
            return nullptr;
        }
        int mid = (left + right + 1) / 2;
        TreeNode *root = new TreeNode();
        root->left = buildTree(head, left, mid - 1);
        root->val = head->val;
        head = head->next;
        root->right = buildTree(head, mid + 1, right);
        return root;
    }

    TreeNode *sortedListToBST(ListNode *head)
    {
        int length = getLength(head);
        return buildTree(head, 0, length - 1);
    }
};
